package com.fourthGroup.fallback;

import com.fourthGroup.feign.OrderClient;
import com.fourthGroup.model.Order;
import com.fourthGroup.model.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class OrderClientFallbackFactory implements FallbackFactory<OrderClient> {
    
    @Override
    public OrderClient create(Throwable cause) {
        return new OrderClient() {
            @Override
            public Order createOrder(Integer pid) {
                log.error("创建订单服务调用失败，商品ID: {}, 错误原因: {}", pid, cause.getMessage());
                Order fallbackOrder = new Order();
                fallbackOrder.setOid(-1L);
                fallbackOrder.setPid(pid);
                fallbackOrder.setStatus(-1); // 表示失败状态
                return fallbackOrder;
            }

            @Override
            public Order queryOrderById(Long oid) {
                log.error("查询订单服务调用失败，订单ID: {}, 错误原因: {}", oid, cause.getMessage());
                Order fallbackOrder = new Order();
                fallbackOrder.setOid(oid);
                fallbackOrder.setStatus(-1); // 表示失败状态
                return fallbackOrder;
            }

            @Override
            public Map<String, Object> queryOrderForAllById(Long oid) {
                log.error("查询订单详情服务调用失败，订单ID: {}, 错误原因: {}", oid, cause.getMessage());
                Map<String, Object> fallbackResult = new HashMap<>();
                Order fallbackOrder = new Order();
                fallbackOrder.setOid(oid);
                fallbackOrder.setStatus(-1); // 表示失败状态
                fallbackResult.put("order", fallbackOrder);
                fallbackResult.put("error", "服务暂时不可用");
                return fallbackResult;
            }

            @Override
            public Order updateOrderStatusById(Long oid) {
                log.error("更新订单状态服务调用失败，订单ID: {}, 错误原因: {}", oid, cause.getMessage());
                Order fallbackOrder = new Order();
                fallbackOrder.setOid(oid);
                fallbackOrder.setStatus(-1); // 表示失败状态
                return fallbackOrder;
            }

            @Override
            public Product queryProductById(Long oid) {
                log.error("查询订单商品服务调用失败，订单ID: {}, 错误原因: {}", oid, cause.getMessage());
                Product fallbackProduct = new Product();
                fallbackProduct.setPid(-1);
                fallbackProduct.setPname("服务暂时不可用");
                return fallbackProduct;
            }
        };
    }
} 